package com.opensource.component.query.repository.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opensource.component.query.mapper.ExtendBaseMapper;
import com.opensource.component.query.repository.ExtendRepository;
import com.opensource.component.query.utils.ObjectCopy;
import com.opensource.component.query.wrapper.LambdaExtendWrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ZL since on 2021/12/18 下午9:23
 */
public abstract class AbstractExtendRepository<M extends ExtendBaseMapper<T>, T> extends
    ServiceImpl<M, T> implements
    ExtendRepository<T> {

  @Override
  public <EV> List<EV> loadExtendList(LambdaExtendWrapper<T> wrapper, Class<EV> clz) {
    List<Map<String, Object>> objectMap = getBaseMapper().selectListExtend(wrapper);
    if (CollectionUtils.isEmpty(objectMap)) {
      return new ArrayList<>();
    }
    return ObjectCopy.map(objectMap, clz);
  }

  @Override
  public < EV> EV loadExtendOne(LambdaExtendWrapper<T> wrapper, Class<EV> clz) {
    Map<String, Object> objectMap = getBaseMapper().selectOneExtend(wrapper);
    if (null == objectMap) {
      return null;
    }
    return ObjectCopy.map(objectMap, clz);
  }

  @Override
  public long loadExtendCount(LambdaExtendWrapper<T> wrapper) {
    return getBaseMapper().selectCountExtend(wrapper);
  }

  @Override
  public <EV> IPage<EV> loadExtendPage(IPage<T> page, LambdaExtendWrapper<T> wrapper,
      Class<EV> clz) {
    IPage<Map<String, Object>> selectPage = getBaseMapper()
        .selectPageExtend(page, wrapper);
    // 获取列表
    List<Map<String, Object>> pageRecords = selectPage.getRecords();
    List<EV> result = ObjectCopy.map(pageRecords, clz);
    Page<EV> returnPage = new Page<>();
    returnPage.setCurrent(page.getCurrent());
    returnPage.setSize(page.getSize());
    returnPage.setTotal(selectPage.getTotal());
    returnPage.setRecords(result);
    return returnPage;
  }


}
